70. Climbing Stairs

1. Question

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

2. Examples

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

3. Constraints

  • 1 <= n <= 45

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/climbing-stairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

dp

class Solution {
    public int climbStairs(int n) {
        if (n <= 0) {
            return 0;
        }
        if (n < 3) {
            return n;
        }

        int[] arr = new int[n + 1];
        arr[1] = 1;
        arr[2] = 2;

        for (int i = 3; i < n + 1; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }

        return arr[n];
    }
}
class Solution {
  public int climbStairs(int n) {
    if (n < 2) {
      return n;
    }

    int a = 1;
    int b = 1;
    int c = 0;

    for (int i = 2; i <= n; i++) {
      c = a + b;
      a = b;
      b = c;
    }

    return b;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""